const app = getApp();

Page({
  data: {
    id: null,
    name: '',
    phone: '',
    region: ['请选择省市区'],
    detail: '',
    isDefault: false
  },

  onLoad(options) {
    if (options.id) {
      this.setData({ id: options.id });
      this.loadAddressDetail(options.id);
    }
  },

  async loadAddressDetail(id) {
    try {
      const res = await app.request({
        url: `/address/${id}/`,
        method: 'GET'
      });

      if (res.code === 200) {
        const { name, phone, province, city, district, detail, is_default } = res.data;
        this.setData({
          name,
          phone,
          region: [province, city, district],
          detail,
          isDefault: is_default
        });
      }
    } catch (error) {
      console.error('获取地址详情失败', error);
      wx.showToast({
        title: '获取地址详情失败',
        icon: 'none'
      });
    }
  },

  handleNameInput(e) {
    this.setData({
      name: e.detail.value
    });
  },

  handlePhoneInput(e) {
    this.setData({
      phone: e.detail.value
    });
  },

  handleRegionChange(e) {
    this.setData({
      region: e.detail.value
    });
  },

  handleDetailInput(e) {
    this.setData({
      detail: e.detail.value
    });
  },

  handleDefaultChange(e) {
    this.setData({
      isDefault: e.detail.value
    });
  },

  async handleSubmit() {
    const { id, name, phone, region, detail, isDefault } = this.data;

    if (!name || !phone || region[0] === '请选择省市区' || !detail) {
      wx.showToast({
        title: '请填写完整信息',
        icon: 'none'
      });
      return;
    }

    if (!/^1[3-9]\d{9}$/.test(phone)) {
      wx.showToast({
        title: '请输入正确的手机号',
        icon: 'none'
      });
      return;
    }

    const data = {
      name,
      phone,
      province: region[0],
      city: region[1],
      district: region[2],
      detail,
      is_default: isDefault
    };

    try {
      const res = await app.request({
        url: id ? `/address/${id}/` : '/address/',
        method: id ? 'PUT' : 'POST',
        data
      });

      if (res.code === 200) {
        wx.showToast({
          title: '保存成功',
          icon: 'success'
        });
        setTimeout(() => {
          wx.navigateBack();
        }, 1500);
      }
    } catch (error) {
      console.error('保存地址失败', error);
      wx.showToast({
        title: '保存失败',
        icon: 'none'
      });
    }
  }
}); 